package hr.chus.alfresco.struts2.webscript;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.mapper.DefaultActionMapper;
import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest;

import com.opensymphony.xwork2.config.ConfigurationManager;

/**
 * 
 * @author Jan Čustović (jan.custovic@gmail.com)
 *
 */
public class WebscriptActionMapper extends DefaultActionMapper {
    
    @Override
    public ActionMapping getMapping(final HttpServletRequest req, final ConfigurationManager configManager) {
        ServletRequest request = req;
        if (request instanceof StrutsRequestWrapper) {
            request = ((StrutsRequestWrapper) req).getRequest();
        }
        
        if (request instanceof WebScriptRequestWrapper) {
            return getMapping((WebScriptRequestWrapper) request, configManager);
        }
        
        return super.getMapping(req, configManager);
    }

	public ActionMapping getMapping(WebScriptRequestWrapper req, ConfigurationManager configurationManager) {
		ActionMapping mapping = new ActionMapping();
        String uri = getUri(req);

        int indexOfSemicolon = uri.indexOf(";");
        uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;

        uri = dropExtension(uri, mapping);
        if (uri == null) {
            return null;
        }

        parseNameAndNamespace(uri, mapping, configurationManager);

        handleSpecialParameters(req, mapping);

        if (mapping.getName() == null) {
            return null;
        }

        parseActionName(mapping);

        return mapping;
	}
	
    protected String getUri(WebScriptRequestWrapper request) {
        WebScriptServletRequest webScriptRequest = request.getWsRequest();
        
        String uri = webScriptRequest.getExtensionPath();
        if (uri != null && !"".equals(uri)) {
            if (!uri.startsWith("/")) {
                uri = "/" + uri;
            }
            return uri;
        }

        uri = webScriptRequest.getServicePath();
        return uri.substring(webScriptRequest.getServiceContextPath().length());
    }

}
